<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
        <el-form-item v-if="!userInfo.orgId" label="所属机构">
          <select-org-tree :value="queryParams.orgId" class="width-120" @orgNodeClick="orgNodeClick"/>
        </el-form-item>
        <el-form-item class="dept-tree-label" label="单位名称" prop="storageName" style="width: 15%">
          <base-dept-tree :dept-attribute-str="'10'" :org-id="queryParams.orgId" :value="queryParams.storageCode"
                          class="width-120" @deptSelect="deptQuerySelect"/>
        </el-form-item>
        <el-form-item label="单位性质" prop="storageType">
          <el-select v-model="queryParams.storageType" class="width-120" clearable
                     placeholder="请选择单位性质"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['storage_type']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="门诊住院标识" label-width="120px" prop="clinicOrVisit">
          <el-select v-model="queryParams.clinicOrVisit" class="width-120" clearable
                     placeholder="请选择门诊住院标识"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['clinic_or_visit']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="发放类型" prop="drugGrantType">
          <el-select v-model="queryParams.drugGrantType" class="width-120" clearable
                     placeholder="请选择药品分类"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['drug_grant_type']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="药品分类" prop="drugClass">
          <el-select v-model="queryParams.drugClass" class="width-120" clearable placeholder="请选择药品分类"
                     @change="handleQuery">
            <el-option v-for="dict in dictDataMap['drug_classification']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPerm="['base:drugStorageDept:add']" plain type="primary" @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPerm="['base:drugStorageDept:export']" plain type="warning" @click="handleExport">
          <template #icon>
            <i-ep-download/>
          </template>
          导出
        </el-button>
        <el-button plain type="danger" @click="refreshCacheDrugStorageDeptFun">
          <template #icon>
            <i-ep-refresh/>
          </template>
          刷新缓存
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :border="true" :data="drugStorageDeptList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="单位名称" prop="storageName"
                       width="150px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="单位性质" prop="storageType"
                       width="120px">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['storage_type']" :value="scope.row.storageType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="是否西药房" prop="storageClass"
                       width="120px">
        <template #default="scope">
          {{
            !scope.row.storageClass ? '无' : scope.row.storageClass === '1' ?
              '中药' : scope.row.storageClass === '2' ? '西药' : '通用'
          }}
        </template>
      </el-table-column>

      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="门诊住院标识" prop="clinicOrVisit"
                       width="120px">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['clinic_or_visit']" :value="scope.row.clinicOrVisit"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" label="发放类型" prop="drugGrantType"
                       width="120px">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['drug_grant_type']"
                         :value="scope.row.drugGrantType ? scope.row.drugGrantType : []"/>
          <!--                    <span v-for="(item ,index) in scope.row.drugClass" :key="index">-->
          <!--                        <dict-data-tag :options="dictDataMap['drug_classification']" :value="item" class="mr5"-->
          <!--                                  style="float: left;"/>-->
          <!--                    </span>-->
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="存放药品分类"
                       min-width="380px" prop="drugClass">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['drug_classification']"
                         :value="scope.row.drugClass ? scope.row.drugClass : []"/>
          <!--                    <span v-for="(item ,index) in scope.row.drugClass" :key="index">-->
          <!--                        <dict-data-tag :options="dictDataMap['drug_classification']" :value="item" class="mr5"-->
          <!--                                  style="float: left;"/>-->
          <!--                    </span>-->
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="虚拟库房" prop="isVirtualStorage" width="70">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isVirtualStorage"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="付款单前缀" prop="disburseNoPrefix"
                       width="110px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="当前付款单号" prop="disburseNoAva"
                       width="110px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库单号前缀" prop="exportNoPrefix"
                       width="120px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库单号前缀" prop="importNoPrefix"
                       width="120px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息" prop="remarks"
                       width="120px"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                       width="420px">
        <template #default="scope">
          <el-button v-hasPerm="['base:drugStorageDept:edit']" type="success"
                     @click="handleUpdate(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button type="success" @click="distributionDept(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
            分配可用科室
          </el-button>
          <el-button type="primary"
                     @click="addWarehouseControl(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
            添加库房对照
          </el-button>
          <el-button v-hasPerm="['base:drugStorageDept:remove']" type="danger"
                     @click="handleDelete(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :total="total" @pagination="getList"/>

    <!-- 添加或修改药品库存单位字典对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="800px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="单位名称" prop="storageName">
              <base-dept-tree :dept-attribute-str="'10'" :org-id="queryParams.orgId" :value="form.storageCode"
                              class="width-120" @deptSelect="deptSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药品类型" prop="storageClass">
              <el-select
                v-model="form.storageClass"
                placeholder="请选择"
                style="width: 240px"
              >
                <el-option
                  key="2"
                  label="西药"
                  value="2"
                />
                <el-option
                  key="1"
                  label="中药"
                  value="1"
                />
                <el-option
                  key="3"
                  label="通用"
                  value="3"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位性质" prop="storageType">
              <el-select v-model="form.storageType" placeholder="请选择单位性质" style="width: 100%;">
                <el-option v-for="dict in dictDataMap['storage_type']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="虚拟库房" prop="isVirtualStorage">
              <el-radio-group v-model="form.isVirtualStorage">
                <el-radio
                  v-for="dict in dictDataMap['sys_yes_no']"
                  :key="dict.dictValue"
                  :border="true"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="存放药品分类" prop="drugClass">
              <el-select v-model="form.drugClass" clearable multiple placeholder="请选择药品分类"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['drug_classification']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门诊住院标识" prop="clinicOrVisit">
              <el-select v-model="form.clinicOrVisit" clearable placeholder="请选择门诊住院标识"
                         style="width: 100%;">
                <el-option v-for="dict in dictDataMap['clinic_or_visit']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放类型" prop="drugGrantType">
              <el-select v-model="form.drugGrantType" clearable multiple placeholder="请选择发放类型"
                         style="width: 100%;">
                <el-option v-for="dict in dictDataMap['drug_grant_type']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款单前缀" prop="disburseNoPrefix">
              <el-input v-model="form.disburseNoPrefix" placeholder="请输入付款单前缀"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前付款单号" prop="disburseNoAva">
              <el-input v-model="form.disburseNoAva" placeholder="请输入当前付款单号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库单号前缀" prop="exportNoPrefix">
              <el-input v-model="form.exportNoPrefix" placeholder="请输入出库单号前缀"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单号前缀" prop="importNoPrefix">
              <el-input v-model="form.importNoPrefix" placeholder="请输入入库单号前缀"/>
            </el-form-item>
          </el-col>
          <!--                    <el-col :span="12">-->
          <!--                        <el-form-item label="是否纳入药柜范畴" prop="ygFlag">-->
          <!--                            <el-input v-model="form.ygFlag" placeholder="请输入是否纳入药柜范畴"/>-->
          <!--                        </el-form-item>-->
          <!--                    </el-col>-->
          <!--                    <el-col :span="12">-->
          <!--                        <el-form-item label="对应药柜护理单元" prop="wardCode">-->
          <!--                            <el-input v-model="form.wardCode" placeholder="请输入对应药柜护理单元"/>-->
          <!--                        </el-form-item>-->
          <!--                    </el-col>-->
          <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
    <storage-vs-dept ref="storageVsDeptRef"/>
    <drug-vs-subordinate ref="drugVsSubordinateRef"/>
  </div>
</template>

<script lang="ts" setup>
import {
  addDrugStorageDept,
  delDrugStorageDept,
  getDrugStorageDept,
  refreshCacheDrugStorageDept,
  selectPageDrugStorageDept,
  updateDrugStorageDept
} from "@/api/drug/drugStorageDept";
import BaseDeptTree from "@/components/Dept/baseDeptTree.vue";
import StorageVsDept from "@/views/drug/drugStorageDept/storageVsDept.vue";
import DrugVsSubordinate from "@/views/drug/drugStorageDept/drugVsSubordinate.vue";
import SelectOrgTree from "@/components/SysOrgTree/selectOrgTree.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";

const {proxy} = getCurrentInstance() as any;
const formRef = ref()
const queryParamsRef = ref()
const storageVsDeptRef = ref()
const drugVsSubordinateRef = ref()
const dictStore = useDictStoreHook();
const dictDataMap = ref<any>(dictStore.isTypeGetData('storage_type', 'drug_classification', 'drug_grant_type', 'clinic_or_visit','sys_yes_no'))
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const buttonLoading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 药品库存单位字典表格数据
const drugStorageDeptList = ref<any>([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  storageName: "",
  storageType: undefined,
  clinicOrVisit: undefined,
  drugGrantType: undefined,

  drugClass: undefined,
  disburseNoPrefix: undefined,
  disburseNoAva: undefined,
  exportNoAva: undefined,
  exportNoPrefix: undefined,
  importNoAva: undefined,
  importNoPrefix: undefined,
  ygFlag: undefined,
  wardCode: undefined,
  orgId: undefined,
  remarks: undefined
})
// 表单参数
const form = ref<any>({
  storageClass: '2'
})
// 表单校验
const rules = ref({
  id: [
    {required: true, message: "主键不能为空", trigger: "blur"}
  ],
  storageCode: [
    {required: true, message: "单位代码不能为空", trigger: "blur"}
  ],
  storageName: [
    {required: true, message: "单位名称不能为空", trigger: "blur"}
  ],
  storageType: [
    {required: true, message: "单位性质不能为空", trigger: "change"}
  ],
  drugGrantType: [
    {required: true, message: "门诊住院标识不能为空", trigger: "change"}
  ],
  clinicOrVisit: [
    {required: true, message: "发放类型不能为空", trigger: "change"}
  ],
  storageClass: [
    {required: true, message: "药品类型不能为空", trigger: "change"}
  ],
  drugClass: [
    {required: true, message: "可存放药品分类不能为空", trigger: "blur"}
  ],
  orgId: [
    {required: true, message: "机构ID不能为空", trigger: "blur"}
  ],
})

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getList()
}

/** 科室树点击事件 */
function deptSelect(node) {
  if (node) {
    form.value.storageCode = node.deptId
    form.value.storageName = node.deptName
  } else {
    form.value.storageCode = ''
    form.value.storageName = ''
  }
}

function deptQuerySelect(node) {
  if (node) {
    queryParams.value.storageCode = node.deptId
    queryParams.value.storageName = node.deptName
  } else {
    queryParams.value.storageCode = ''
    queryParams.value.storageName = ''
  }
  handleQuery();
}

// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId
  getList()
}

/** 查询药品库存单位字典列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  selectPageDrugStorageDept(queryParams.value).then((response: any) => {
    drugStorageDeptList.value = response.rows;
    total.value = response.total;
    drugStorageDeptList.value.forEach(item => {
      item.drugClass = item.drugClass ? item.drugClass.split(',') : []
      item.drugGrantType = item.drugGrantType ? item.drugGrantType.split(',') : []
    })
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    storageCode: undefined,
    storageName: undefined,
    storageType: undefined,
    drugClass: undefined,
    disburseNoPrefix: undefined,
    disburseNoAva: undefined,
    exportNoAva: undefined,
    exportNoPrefix: undefined,
    importNoAva: undefined,
    importNoPrefix: undefined,
    ygFlag: undefined,
    wardCode: undefined,
    orgId: queryParams.value.orgId,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remarks: undefined,
    drugGrantType: undefined,
    clinicOrVisit: undefined,
    isVirtualStorage: 'N'
  };
  nextTick(() => {
    formRef.value.resetFields()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  queryParams.value.storageCode = ''
  queryParams.value.storageName = ''
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  open.value = true;
  reset();
  title.value = "添加药品库存单位字典";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  const id = row.id || ids.value
  getDrugStorageDept(id).then(response => {
    form.value = response.data;
    // 可用药品分类 字符串转 数组，用于回显
    form.value.drugClass ? form.value.drugClass = form.value.drugClass.split(',') : []
    form.value.drugGrantType ? form.value.drugGrantType = form.value.drugGrantType.split(',') : []
    title.value = "修改药品库存单位字典";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      form.value.drugClass = form.value.drugClass.join(',')
      form.value.drugGrantType = form.value.drugGrantType.join(',')
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateDrugStorageDept(form.value).then(() => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addDrugStorageDept(form.value).then(() => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsThis = row.id || ids.value;
  ElMessageBox.confirm(`是否确认删除药品库存单位字典为"${row.storageName}"的数据？`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugStorageDept(idsThis).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  // download('base/drugStorageDept/export', {
  //     ...queryParams
  // }, `drugStorageDept_${new Date().getTime()}.xlsx`)
}

/** 分配可用科室 */
function distributionDept(row) {
  storageVsDeptRef.value.storageVsDeptShow(toRaw(row))
}

/**
 * 添加库房对照
 * @param row
 */
function addWarehouseControl(row: any) {
  drugVsSubordinateRef.value.getRowList(row)
}

function refreshCacheDrugStorageDeptFun() {
  refreshCacheDrugStorageDept().then((res: any) => {
    ElMessage.success(res.msg);
  })
}
</script>

<script lang="ts">
export default {
  name: "DrugStorageDept"
}
</script>

<style scoped>
:deep(.vue-treeselect__control) {
  height: 30px !important;
  margin-bottom: 13px;
}

:deep(.vue-treeselect__single-value) {
  top: -2px
}
</style>
